﻿using FB.Mvc.Controllers;
using FB.Services;
using FCDB.Entity;
using FCDB.Repository;
using FCDB.Web.Models;
using FCDB.WEB.Helpers;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace FCDB.WEB.Controllers
{
    [FB.Membership.Annotations.AuthorizeOnly]
    public class WordController : BaseController
    {
        FormRepository formRepository = new FormRepository();
        private Logger logger = NLog.LogManager.GetCurrentClassLogger();
        //
        // GET: /Word/


        public static List<String> AgreementNameList { get; set; }
        public static List<String> FallNameList { get; set; }
        public ActionResult SelectTempldate(int templateType = 0)
        {
            String AgreementPath = null;
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            if (templateType == 0)
            {
                if (AgreementNameList == null)
                {
                    AgreementPath = Server.MapPath(@"~\WordTemplate\Agreement\");
                    string[] fileList = Directory.GetFiles(AgreementPath, "*.doc");
                    List<String> list = new List<string>();
                    foreach (var item in fileList)
                    {
                        char[] delimiterChars = { '.', '\\' };
                        string[] Mystr = item.Split(delimiterChars);
                        string sheetName = Mystr[Mystr.Length - 2];
                        list.Add(sheetName);
                    }
                    AgreementNameList = list;
                }
                return PartialView(AgreementNameList);
            }
            else
            {
                if (FallNameList == null)
                {
                    AgreementPath = Server.MapPath(@"~\WordTemplate\Fall\");
                    string[] fileList = Directory.GetFiles(AgreementPath, "*.doc");
                    List<String> list = new List<string>();
                    foreach (var item in fileList)
                    {
                        char[] delimiterChars = { '.', '\\' };
                        string[] Mystr = item.Split(delimiterChars);
                        string sheetName = Mystr[Mystr.Length - 2];
                        list.Add(sheetName);
                    }
                    FallNameList = list;
                }
                return PartialView(FallNameList);
            }
        }

        public ActionResult IsExistAgreement(long formID)
        {
            String filename = Server.MapPath(@"~\ContractFolder\Agreement\" + formID + ".doc");
            JsonResult jsonResult = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            jsonResult.Data = System.IO.File.Exists(filename);
            return jsonResult;
        }
        public ActionResult IsExistFall(long formID)
        {
            String filename = Server.MapPath(@"~\ContractFolder\Fall\" + formID + ".doc");
            JsonResult jsonResult = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            jsonResult.Data = System.IO.File.Exists(filename);
            return jsonResult;
        }
        public ActionResult PrintAgreement(long formID, String templateName)
        {
            JsonResult jsonResult = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            templateName = templateName.Trim();
            RtnMsg rtn = new RtnMsg() { Status = 0, ExtentInfo = "", Message = "" };
            string SaveDocPath = Server.MapPath(@"~\ContractFolder\Agreement\" + formID + ".doc");
            if (System.IO.File.Exists(SaveDocPath))
            {
                rtn.Status = 0;
                jsonResult.Data = rtn;
                return jsonResult;
            }
            FormCDB formCDB = formRepository.Get<FormCDB>(formID);
            if (formCDB == null)
            {
                rtn.Status = 1;
                rtn.Message = "保函不存在";
                jsonResult.Data = rtn;
                return jsonResult;
            }
              
            templateName = templateName + ".doc";
            string FilePath = Server.MapPath(@"~\WordTemplate\Agreement\" + templateName);
            try
            {  
                foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                {
                    p.Kill();
                }
                if (System.IO.File.Exists(SaveDocPath))
                    System.IO.File.Delete(SaveDocPath);
                System.IO.File.Copy(FilePath, SaveDocPath);
                WordHelper wiw = new WordHelper();
                wiw.OpenDocument(SaveDocPath);
                WriteIntoDocument(wiw, formCDB);
                wiw.Save_CloseDocument();
                rtn.Status = 0;
                jsonResult.Data = rtn;
                return jsonResult;
            }
            catch (Exception ex)
            {
                logger.Error(ex);

                rtn.Status = 1;
                rtn.Message = "生成保函异常" + ex.Message; ;
                jsonResult.Data = rtn;
                return jsonResult;
            }


        }

        public ActionResult DeleteAgreement(long formID)
        {
            JsonResult jsonResult = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            RtnMsg rtn = new RtnMsg() { Status = 0, ExtentInfo = "", Message = "" };
            string SaveDocPath = Server.MapPath(@"~\ContractFolder\Agreement\" + formID + ".doc");
            if (System.IO.File.Exists(SaveDocPath))
            {
                System.IO.File.Delete(SaveDocPath);
                rtn.Status = 0;
                jsonResult.Data = rtn;

            }
            return jsonResult;
        }

        public ActionResult DeleteFall(long formID)
        {
            JsonResult jsonResult = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            RtnMsg rtn = new RtnMsg() { Status = 0, ExtentInfo = "", Message = "" };
            string SaveDocPath = Server.MapPath(@"~\ContractFolder\Fall\" + formID + ".doc");
            if (System.IO.File.Exists(SaveDocPath))
            {
                System.IO.File.Delete(SaveDocPath);


            }
            rtn.Status = 0;
            jsonResult.Data = rtn;
            return jsonResult;
        }
        public ActionResult GetAgreement(long formID)
        {
            String filename = Server.MapPath(@"~\ContractFolder\Agreement\" + formID + ".doc");
            return File(filename, "application/octet-stream");
        }
        public ActionResult GetFall(long formID)
        {
            String filename = Server.MapPath(@"~\ContractFolder\Fall\" + formID + ".doc");
            return File(filename, "application/octet-stream");

        }

        private void WriteBookmarker(WordHelper wordhelper, String bookmarker, String value)
        {
            if(!String.IsNullOrEmpty(value))
            { 
              wordhelper.WriteIntoDocument(bookmarker, value);
            }
        }
        private String[] RemoveEmptyItem(String[] array)
        {
            List<String> list = new List<string>();
            foreach (var item in array)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    list.Add(item);
                }
            }
            return list.ToArray();
        }
        public string numtoUpper(int num)
        {
            String str = num.ToString();
            string rstr = "";
            int n;
            for (int i = 0; i < str.Length; i++)
            {
                n = Convert.ToInt16(str[i].ToString());//char转数字,转换为字符串，再转数字
                switch (n)
                {
                    case 0: rstr = rstr + "〇"; break;
                    case 1: rstr = rstr + "一"; break;
                    case 2: rstr = rstr + "二"; break;
                    case 3: rstr = rstr + "三"; break;
                    case 4: rstr = rstr + "四"; break;
                    case 5: rstr = rstr + "五"; break;
                    case 6: rstr = rstr + "六"; break;
                    case 7: rstr = rstr + "七"; break;
                    case 8: rstr = rstr + "八"; break;
                    default: rstr = rstr + "九"; break;
                }

            }
            return rstr;
        }
        private void WriteIntoDocument(WordHelper wordhelper, FormCDB form)
        {
            #region 正常书签
            WriteBookmarker(wordhelper, "编号", form.pact_no);
            WriteBookmarker(wordhelper, "案号", form.CaseNumber);
            WriteBookmarker(wordhelper, "生成保函时间月份", form.GuaranteeTime.HasValue ? form.GuaranteeTime.Value.Month.ToString() : "");
            WriteBookmarker(wordhelper, "生成保函时间日期", form.GuaranteeTime.HasValue ? form.GuaranteeTime.Value.Day.ToString() : "");
            WriteBookmarker(wordhelper, "仲裁案号", form.ArbitrationNumber);
            WriteBookmarker(wordhelper, "申请人", form.ApplyUser);
            WriteBookmarker(wordhelper, "申请人1", form.ApplyUser);
            WriteBookmarker(wordhelper, "申请人2", form.ApplyUser);
            WriteBookmarker(wordhelper, "申请人3", form.ApplyUser);
            WriteBookmarker(wordhelper, "被申请人", form.Respondent);
            WriteBookmarker(wordhelper, "被申请人1", form.Respondent);
            WriteBookmarker(wordhelper, "申请人担保情况", form.ApplyGuarantee);
            WriteBookmarker(wordhelper, "法院名称", form.Court);
            WriteBookmarker(wordhelper, "法院名称1", form.Court);
            WriteBookmarker(wordhelper, "法院名称2", form.Court);
            WriteBookmarker(wordhelper, "所属法院", form.Court);
            WriteBookmarker(wordhelper, "所属法院1", form.Court);
            WriteBookmarker(wordhelper, "所属法院2", form.Court);
            WriteBookmarker(wordhelper, "标的金额", form.Amount.HasValue ? form.Amount.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "标的金额1", form.Amount.HasValue ? form.Amount.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "标的金额2", form.Amount.HasValue ? form.Amount.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "标的金额大写", form.Amount.HasValue ? StringUtil.ToUpperChineseCurrency(form.Amount.Value) : "");
            WriteBookmarker(wordhelper, "标的金额大写1", form.Amount.HasValue ? StringUtil.ToUpperChineseCurrency(form.Amount.Value) : "");
            WriteBookmarker(wordhelper, "标的金额大写2", form.Amount.HasValue ? StringUtil.ToUpperChineseCurrency(form.Amount.Value) : "");
            WriteBookmarker(wordhelper, "费率", form.Rate.HasValue ? form.Rate.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "合同收款", form.ContractAmount.HasValue ? form.ContractAmount.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "合同收款大写", form.ContractAmount.HasValue ? StringUtil.ToUpperChineseCurrency(form.ContractAmount.Value) : "");
            WriteBookmarker(wordhelper, "应付佣金", form.PayableAmount.HasValue ? form.PayableAmount.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "应付佣金大写", form.PayableAmount.HasValue ? StringUtil.ToUpperChineseCurrency(form.PayableAmount.Value) : "");
            WriteBookmarker(wordhelper, "实际费率", form.ActualRate.HasValue ? form.ActualRate.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "实际收费", form.ActualCharge.HasValue ? form.ActualCharge.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "实际收费大写", form.ActualCharge.HasValue ? StringUtil.ToUpperChineseCurrency(form.ActualCharge.Value) : "");
            WriteBookmarker(wordhelper, "联保情况", form.GuaranteeSituation);
            WriteBookmarker(wordhelper, "申请人身份证或法定代表人", form.ApplyIDCard);
            WriteBookmarker(wordhelper, "申请人地址", form.ApplyAddress);
            WriteBookmarker(wordhelper, "案由", form.CauseOfAction);
            WriteBookmarker(wordhelper, "保证金", form.Bond.HasValue ? form.Bond.Value.ToString("#0.00") : "");
            WriteBookmarker(wordhelper, "保证金大写", form.Bond.HasValue ? StringUtil.ToUpperChineseCurrency(form.Bond.Value) : "");
            WriteBookmarker(wordhelper, "联保公司法定代表人", form.CompanyGuarantee);
            WriteBookmarker(wordhelper, "联保公司地址", form.CompanyAddress);
            WriteBookmarker(wordhelper, "联保公司电话", form.CompanyTel);
            WriteBookmarker(wordhelper, "保险合作情况", form.InsuranceCooperation);
            WriteBookmarker(wordhelper, "业务备注", form.BusinessRemark);
            WriteBookmarker(wordhelper, "财务实收金额", form.financiaAmount.HasValue ? form.financiaAmount.Value.ToString("#0.000") : "");
          
            WriteBookmarker(wordhelper, "实付中介费", form.Intermediary.HasValue ? form.Intermediary.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "实际返佣时", form.RebateTime.HasValue ? form.RebateTime.Value.ToString("yyyy年MM月dd日") : "");
            WriteBookmarker(wordhelper, "收费月份", form.ChargingDate.HasValue ? form.ChargingDate.Value.ToString("MM月") : "");
            WriteBookmarker(wordhelper, "保函生产时间", form.GuaranteeTime.HasValue ? form.GuaranteeTime.Value.ToString("yyyy年MM月dd日") : "");
            WriteBookmarker(wordhelper, "财务收款时间", form.ChargingDate.HasValue ? form.ChargingDate.Value.ToString("yyyy年MM月dd日") : "");
            WriteBookmarker(wordhelper, "主审法官", form.Judge);
            WriteBookmarker(wordhelper, "龙岗数据报送", form.DataSend);
            WriteBookmarker(wordhelper, "财产线索", form.PropertyClues);
            #region  2017-12-10
            WriteBookmarker(wordhelper, "联保乙公司名称", form.CompanyGuarantee);
            WriteBookmarker(wordhelper, "联保乙方代表人", form.CompanyUser);
            WriteBookmarker(wordhelper, "联保总标的金额", form.ZBjine.HasValue?form.ZBjine.Value.ToString("#0.000"):"");
            WriteBookmarker(wordhelper, "我司担保标的金额", form.DBjine.HasValue ? form.DBjine.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "我司所占比例", form.ZBbili.HasValue?form.ZBbili.Value.ToString("#0.000"):"");
            WriteBookmarker(wordhelper, "我司合同收费", form.XYfeiyong.HasValue ? form.XYfeiyong.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "他司合同收费", form.TSXYfeiyong.HasValue ? form.XYfeiyong.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "他司所占比例", form.FCZbili.HasValue ? form.TSXYfeiyong.Value.ToString("#0.000") : "");
            WriteBookmarker(wordhelper, "保险公司名称", form.InsuranceCooperation);
           
            #endregion 
            #endregion
            #region 特殊书签
            #region 对公账号信息
            if (form.InvoiceType > 0)
            {
                WriteBookmarker(wordhelper, "对公账号信息", "（乙方收款账户为，账户名：深圳市富昌融资担保有限公司，开户行：工行深圳市分行友谊支行，账号：4000 0258 1920 0267 437。）");
            }
            #endregion
            #region 申请人资料&&被担保人资料
            StringBuilder strBuilder = new StringBuilder();
            if (!String.IsNullOrEmpty(form.ApplyUser))
            {
                String[] ApplyUserList = form.ApplyUser.Split('、');
                ApplyUserList = RemoveEmptyItem(ApplyUserList);
                String[] ApplyIDCardList = form.ApplyIDCard.Split('、');
                ApplyIDCardList = RemoveEmptyItem(ApplyIDCardList);
                String[] ApplyAddresList = form.ApplyAddress.Split('、');
                ApplyAddresList = RemoveEmptyItem(ApplyAddresList);
                for (int index = 0; index < ApplyUserList.Count(); index++)
                {
                    if (!String.IsNullOrEmpty(ApplyUserList[index]))
                    {
                        strBuilder.AppendLine(String.Format("甲方(申请人{0}) ：{1}", (ApplyUserList.Count() > index && ApplyUserList.Count() > 1 ? numtoUpper(index + 1) : ""), ApplyUserList.Count() > index ? ApplyUserList[index] : ""));
                        strBuilder.AppendLine(String.Format("法定代表人/身份证号码：{0}", ApplyIDCardList.Count() > index ? ApplyIDCardList[index] : ""));
                        strBuilder.AppendLine(String.Format("地址：{0}\n",  ApplyAddresList.Count() > index ? ApplyAddresList[index] : ""));
                    }

                }
                WriteBookmarker(wordhelper, "申请人资料", strBuilder.ToString());
                strBuilder = new StringBuilder();
                for (int index = 0; index < ApplyUserList.Count(); index++)
                {
                    if (!String.IsNullOrEmpty(ApplyUserList[index]))
                    {
                        strBuilder.AppendLine(String.Format("被担保人{0} ：{1}", (ApplyUserList.Count() > index && ApplyUserList.Count() > 1 ? numtoUpper(index + 1) : ""), ApplyUserList.Count() > index ? ApplyUserList[index] : ""));
                        strBuilder.AppendLine(String.Format("法定代表人/身份证号码：{0}",  ApplyIDCardList.Count() > index ? ApplyIDCardList[index] : ""));
                        strBuilder.AppendLine(String.Format("地址：{0}\n",  ApplyAddresList.Count() > index ? ApplyAddresList[index] : ""));
                    }
                }
                WriteBookmarker(wordhelper, "被担保人资料", strBuilder.ToString());
            }
            #endregion

            #endregion  
            #region 补充2017-11-25
            strBuilder = new StringBuilder();
            String GuaranteeType = String.IsNullOrEmpty(form.GuaranteeType)?"":form.GuaranteeType.Trim();
            
            if (GuaranteeType == "联保案件")
            {
                strBuilder.AppendLine(string.Format("乙方(二)：{0}", form.CompanyGuarantee));
                strBuilder.AppendLine(string.Format("法定代表人：{0}", form.CompanyUser));
                strBuilder.AppendLine(string.Format("地址：{0}",form.CompanyAddress ));
                strBuilder.AppendLine(string.Format("联系电话：{0}\n",form.CompanyTel ));
                WriteBookmarker(wordhelper, "乙方公司信息", strBuilder.ToString());
            } 
            strBuilder = new StringBuilder();
            if(form.GuaranteeType == "联保案件")
            {
                strBuilder.AppendLine(string.Format("乙方(二)：{0}(公章)", form.CompanyGuarantee));
                strBuilder.AppendLine(string.Format("法定代表人：{0}(签字)", "___________________"));
                strBuilder.AppendLine(string.Format("联系人：{0}", "___________________"));
                strBuilder.AppendLine(string.Format("联系电话：{0}\n", form.CompanyTel));
                WriteBookmarker(wordhelper, "乙方落款信息", strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            if (form.GuaranteeType == "联保案件")
            {
                strBuilder.AppendLine(string.Format("担保人（二）：{0}", form.CompanyGuarantee));
                strBuilder.AppendLine(string.Format("法定代表人：{0}\n", form.CompanyUser)); 
                WriteBookmarker(wordhelper, "担保人公司信息", strBuilder.ToString());
            }
            if (form.GuaranteeType == "联保案件")
            {
                strBuilder.AppendLine(string.Format("担保人（二）：{0}(盖章)", form.CompanyGuarantee));
                strBuilder.AppendLine(string.Format("负责人或授权代理人(签字)：{0}", "___________________"));
                strBuilder.AppendLine(string.Format("       签发日期：{0}\n",form.GuaranteeTime.HasValue ? form.GuaranteeTime.Value.ToString("yyyy年MM月dd日"):""));
                WriteBookmarker(wordhelper, "担保人落款信息", strBuilder.ToString());
            }
          
            #endregion 


        }
        public ActionResult PrintFall(long formID, String templateName)
        {
            JsonResult jsonResult = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            templateName = templateName.Trim();
            RtnMsg rtn = new RtnMsg() { Status = 0, ExtentInfo = "", Message = "" };
            string SaveDocPath = Server.MapPath(@"~\ContractFolder\Fall\" + formID + ".doc");
            if (System.IO.File.Exists(SaveDocPath))
            {
                rtn.Status = 0;
                jsonResult.Data = rtn;
                return jsonResult;
            }
            FormCDB formCDB = formRepository.Get<FormCDB>(formID);
            if (formCDB == null)
            {
                rtn.Status = 1;
                rtn.Message = "保函不存在";
                jsonResult.Data = rtn;
                return jsonResult;
            }
            formCDB.GuaranteeTime = DateTime.Now;
            formRepository.SaveChagnes();
            templateName = templateName + ".doc";
            string FilePath = Server.MapPath(@"~\WordTemplate\Fall\" + templateName);
            WordHelper wiw = new WordHelper();
            try
            {
                foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                {
                    p.Kill();
                }
                if (System.IO.File.Exists(SaveDocPath)) 
                    System.IO.File.Delete(SaveDocPath); 
                System.IO.File.Copy(FilePath, SaveDocPath);
                wiw.OpenDocument(SaveDocPath);
                WriteIntoDocument(wiw, formCDB);
                wiw.Save_CloseDocument();
                rtn.Status = 0;
                jsonResult.Data = rtn;
                return jsonResult;
            }
            catch (Exception ex)
            {
                wiw.CloseDocument();
                logger.Error(ex);
                rtn.Status = 1;
                rtn.Message = "生成协议异常：" + ex.Message;
                jsonResult.Data = rtn;
                return jsonResult;
            }

        }

    }
}
